var express = require('express');
var bodyParser = require('body-parser')
var compression = require('compression');
var cookieParser = require('cookie-parser');
var installApi = require('./middlewares/api');
var history = require('connect-history-api-fallback');
var logger = require('morgan');
var path = require('path');
var nunjucks = require('nunjucks');
var settings = require('../config');
var glob = require('glob');
var app = express();
app.use(history());
var options = {
    maxAge: 864000000
};
// gzip 压缩
function shouldCompress(req, res) {
    if (req.headers['x-no-compression']) {
        // 这里就过滤掉了请求头包含'x-no-compression'
        return false
    }
    return compression.filter(req, res)
}

app.use(compression({
    filter: shouldCompress
}));
app.use(logger('dev'));

const env = new nunjucks.Environment(new nunjucks.FileSystemLoader('./views'), {
    autoescape: false
})
env.express(app);
app.set('view engine', 'html');
app.set('view cache', false);
app.use(express.json());

installApi(app);
const controllers = glob.sync(path.join(__dirname, '../src/controllers/**/*.js'))
controllers.forEach((controller) => {
    require(controller)(app)
});
app.use(express.urlencoded({ extended: false, limit: '10mb' }));
app.use(cookieParser());
app.use(bodyParser.json({
    type: ['json', 'application/csp-report']
}));

app.use(express.static(path.join(__dirname, '../views'), options));

/**
 * RequestHandler(req, res, next)
 * */
app.use((req, res, next) => {
    // 路由404
    res.status(404).render('404.html', {
        url: req.originalUrl,
        error: 'Not found'
    })
})

module.exports = app;